package org.example.salary.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

/**
 * @author : yurui
 * @date : 2024/6/2
 * @TIME : 12:22
 * @project : AuthDemo
 */

@Configuration
public class MyResourceServerConfig extends ResourceServerConfigurerAdapter {

    public static final String RESOURCE_ID = "salary";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID)
                .tokenServices(tokenServices())
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        System.out.println("运行了MyResourceServerConfig-configure(HttpSecurity http)2222222222222222");
        http.csrf().disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //因为spring security有访问权的投票机制，默认是AffirmativeBased机制，存在一个权限符合就可以进行访问
                //所以即使MyWebSecurityConfig中设置了另外一个访问权限，通关token的方式也可以进行访问
                .antMatchers("/salary/**")
                .access("#oauth2.hasScope('all')");

    }

    //配置access_token远程验证策略
    public ResourceServerTokenServices tokenServices(){
        RemoteTokenServices services = new RemoteTokenServices();
        services.setCheckTokenEndpointUrl("http://localhost:53020/uua/oauth/check_token");
        services.setClientId("c1");
        services.setClientSecret("yurui");
        return services;
    }
}
